package com.taxinfo.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.taxinfo.AbstractApp;
import com.taxinfo.App;
import com.taxinfo.AppState;
import com.taxinfo.common.ClientSession;
import com.taxinfo.component.CustomSplash;
import com.taxinfo.component.alert.MyAlert;
import com.taxinfo.config.ImageSrc;
import com.taxinfo.fxml.AbstractFxmlView;
import com.taxinfo.pojo.dto.LoginDto;
import com.taxinfo.pojo.vo.RobotOutParams;
import com.taxinfo.pojo.vo.RobotPlanBean;
import com.taxinfo.pojo.vo.RobotProjectInfoBean;
import com.taxinfo.pojo.vo.StandardSub;
import com.taxinfo.service.LoginService;
import com.taxinfo.service.StandardSubService;
import com.taxinfo.utils.*;
import com.taxinfo.view.UpdatePasswordView;
import com.taxinfo.view.WelcomeView;
import com.taxinfo.view.dataImport.DataImportTab;
import com.taxinfo.view.declaration.DecFileViewTable;
import com.taxinfo.view.declaration.DeclarationRecordTab;
import com.taxinfo.view.standard.StandardSubTab;
import com.taxinfo.view.subjectMatch.SubjectMatchTab;
import de.felixroske.jfxsupport.FXMLController;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.json.JsonParser;

import javax.swing.*;
import java.io.IOException;
import java.net.URL;
import java.util.*;

@FXMLController
public class MainController implements Initializable {

    private final Logger logger = LoggerFactory.getLogger(MainController.class);

    private static final double IMG_SIZE = 30;


    private static final TabPane rootTabPane;

    static {
        rootTabPane = new TabPane();
        rootTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
    }

    @FXML
    private ToolBar toolBar;

    /**
     * 根布局
     */
    @FXML
    private BorderPane bp_root;

    @FXML
    private Button btn_shift;

    @FXML
    private Button btn_setting;

    @FXML
    private Button btn_exit;

    @FXML
    private VBox leftMenuVb;
    @FXML
    public Button btn_baseSub;
    @FXML
    public Button btn_subMap;
    @FXML
    public Button btn_import;
    @FXML
    public Button btn_decRecord;
    @FXML
    public Button btn_help;

    @FXML
    public HBox arrow1;
    @FXML
    public HBox arrow2;
    @FXML
    public HBox arrow3;

    @FXML
    public HBox sbxxId;

    @FXML
    public HBox companyName;
    @FXML
    public HBox taxNo;



    @Override
    public void initialize(URL location, ResourceBundle resources) {
        startSyncFileTask();
        initTopMenu();
        //initLeftMenu();
        ImageView img_arrow1 = new ImageView(ImageSrc.ARROW_ICON); //设置密码图标
        arrow1.setStyle("-fx-alignment: center");
        arrow1.getChildren().add(img_arrow1);
        ImageView img_arrow2 = new ImageView(ImageSrc.ARROW_ICON); //设置密码图标
        arrow2.setStyle("-fx-alignment: center");
        arrow2.getChildren().add(img_arrow2);
        ImageView img_arrow3 = new ImageView(ImageSrc.ARROW_ICON); //设置密码图标
        arrow3.setStyle("-fx-alignment: center");
        arrow3.getChildren().add(img_arrow3);
        bp_root.setStyle("-fx-padding: -1px");
        bp_root.setCenter(rootTabPane);
       addTab(DataImportTab.getInstance());
        LoginDto loginDto = (LoginDto) ClientSession.getAttribute("user");
        Label label = new Label("企业名称:");
        companyName.getChildren().add(label);
        companyName.setStyle("-fx-font-size: 16px;  -fx-font-style: bold; -fx-font-weight: 50; ");
        String sCompanyName =loginDto.getCompanyName();
        if(StringUtils.isNotBlank(loginDto.getSoftName())){
            String zz = "";
            if("0".equals(loginDto.getIndexStandardType())){
                zz = "财务报表2007旧准则";
            }else if("1".equals(loginDto.getIndexStandardType())){
                zz = "财务报表2019新准则";
            }else if("2".equals(loginDto.getIndexStandardType())){
                zz = "财务报表2013小企业会计准则";
            }
            sCompanyName =sCompanyName.concat("【").concat(loginDto.getSoftName()).concat("】,【".concat(zz).concat("】"));
        }
        companyName.getChildren().add(new Label(sCompanyName));
        taxNo.getChildren().add(new Label("统一社会信用代码:"));
        taxNo.getChildren().add(new Label(loginDto.getCreditCode()));
        taxNo.setStyle("-fx-font-size: 16px; -fx-font-weight: 50; -fx-font-style: bold ");
    }

    /**
     * 添加Tab到主TabPane
     *
     * @param tab tab面板
     */
    public static void addTab(Tab tab) {
        ObservableList<Tab> tabs = rootTabPane.getTabs();
        if (!tabs.contains(tab)) {
            tabs.add(tab);
        }
        rootTabPane.getSelectionModel().select(tab);
    }

    /**
     * 从主TabPane移除Tab
     *
     * @param tab tab面板
     */
    public static void removeTab(Tab tab) {
        ObservableList<Tab> tabs = rootTabPane.getTabs();
        tabs.remove(tab);
    }

    private void initTopMenu() {
        ImageView img_logo = new ImageView(ImageSrc.lOGO_PATH); //设置密码图标
        UIUtil.setImageViewSize(img_logo, IMG_SIZE+40);
        sbxxId.getChildren().add(img_logo);
        // 初始化顶部菜单图标
        ImageView img_passwd = new ImageView(ImageSrc.PASSWD_PATH); //设置密码图标
        ImageView img_setting = new ImageView(ImageSrc.SETTING_PATH); //系统设置
        ImageView img_exit = new ImageView(ImageSrc.EXIT_PATH); // 退出图标
        ImageView baseSubject = new ImageView(ImageSrc.SHIFT_PATH); // 标准科目
        ImageView subMatch = new ImageView(ImageSrc.SUBMAP_PATH); // 科目映射
        ImageView impRecord = new ImageView(ImageSrc.IMP_RECORD_PATH); //余额表导入
        ImageView decRecord = new ImageView(ImageSrc.BACKUPS_PATH); //申报记录
        ImageView telImg = new ImageView(ImageSrc.TEL_PATH); //在线帮助

        UIUtil.setImageViewSize(baseSubject, IMG_SIZE);
        UIUtil.setImageViewSize(subMatch, IMG_SIZE);
        UIUtil.setImageViewSize(impRecord, IMG_SIZE);
        UIUtil.setImageViewSize(decRecord, IMG_SIZE);
        UIUtil.setImageViewSize(telImg, IMG_SIZE);
        UIUtil.setImageViewSize(img_passwd, IMG_SIZE);
        UIUtil.setImageViewSize(img_setting, IMG_SIZE);
        UIUtil.setImageViewSize(img_exit, IMG_SIZE);

        btn_help.setGraphic(telImg);
        btn_help.setOnAction(event -> {
            Dialog<String> dialog = new Dialog<>();
            dialog.setTitle("联系信息");
            dialog.setResizable(true);
            DialogPane pane = dialog.getDialogPane();
            pane.setPrefSize(300,200);
            Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
            stage.getIcons().add(new Image(ImageSrc.lOGO_PATH));
            pane.getButtonTypes().add(ButtonType.OK);
            GridPane gridPane = new GridPane();
            gridPane.setVgap(20);
            gridPane.setStyle("-fx-font-size: 16px; -fx-font-weight: 50; -fx-margin-top: 10px;-fx-margin-bottom:10px");
            GridPane.setHalignment(gridPane, HPos.CENTER);
            ImageView emailImg = new ImageView(ImageSrc.EMAIL_PATH); //设置密码图标
            Label email = new Label(" 联系邮箱: admin@hthuiyou.com");
            email.setGraphic(emailImg);
            gridPane.add(email,1,1);
            ImageView telephoneImg = new ImageView(ImageSrc.TEL_PATH); //设置密码图标
            //Label tel = new Label(" 联系电话: 186XXXXXXX");
            //tel.setGraphic(telephoneImg);
           // gridPane.add(tel,1,2);
            pane.setContent(gridPane);
            dialog.showAndWait();
        });
        btn_decRecord.setGraphic(decRecord);
        btn_decRecord.setOnMouseClicked(event -> addTab(DeclarationRecordTab.getInstance()));
        btn_import.setGraphic(impRecord);
        btn_import.setOnMouseClicked(event -> addTab(DataImportTab.getInstance()));
        btn_subMap.setGraphic(subMatch);
        btn_subMap.setOnMouseClicked(event -> addTab(SubjectMatchTab.getInstance()));
        btn_baseSub.setGraphic(baseSubject);
        btn_baseSub.setOnMouseClicked(event -> addTab(StandardSubTab.getInstance()));
        btn_shift.setGraphic(img_passwd);
        btn_exit.setGraphic(img_exit);
        btn_setting.setGraphic(img_setting);
        btn_exit.setOnMouseClicked(event ->   System.exit(0));

        btn_shift.setOnAction(event -> {

            Dialog<String> dialog = new Dialog<>();
            dialog.setTitle("修改密码");
            dialog.setResizable(true);
            DialogPane pane = dialog.getDialogPane();
            pane.setPrefSize(300,200);
            Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
            stage.getIcons().add(new Image(ImageSrc.lOGO_PATH));
            GridPane gridPane = new GridPane();
            gridPane.setVgap(10);
            gridPane.setAlignment(Pos.CENTER);

            Label lUser = new Label("用户名: ");
            lUser.setAlignment(Pos.CENTER_RIGHT);
            gridPane.add(lUser,1,1);
            LoginDto loginDto =(LoginDto)ClientSession.getAttribute("user");
            TextField tfUser = new TextField(loginDto.getId());
            tfUser.setPrefHeight(30);
            tfUser.setEditable(false);
            gridPane.add(tfUser,2,1);

            Label lPasswd = new Label("新密码: ");
            lPasswd.setAlignment(Pos.CENTER_RIGHT);
            gridPane.add(lPasswd,1,2);
            PasswordField tfPasswd = new PasswordField();
            tfPasswd.setPrefHeight(30);
            gridPane.add(tfPasswd,2,2);

            Label lPasswdOK = new Label("确认密码: ");
            lPasswdOK.setAlignment(Pos.CENTER_RIGHT);
            gridPane.add(lPasswdOK,1,3);
            PasswordField tfPasswdOk = new PasswordField();
            tfPasswdOk.setPrefHeight(30);
            gridPane.add(tfPasswdOk,2,3);
            pane.setContent(gridPane);

            // 设置按钮和事件处理（可选）
            ButtonType buttonTypeOK = new ButtonType("确定");
            pane.getButtonTypes().add(buttonTypeOK);
            pane.getButtonTypes().add(ButtonType.CANCEL);
            dialog.setResultConverter(dialogButton -> dialogButton == buttonTypeOK ? "OK" : null);
            dialog.showAndWait().ifPresent(response -> {
                if ("OK".equals(response)) {
                    if(StringUtils.isBlank(tfPasswd.getText().trim())) {
                        new MyAlert(Alert.AlertType.ERROR, "新密码不能为空").show();
                        return;
                    }
                    if(StringUtils.isBlank(tfPasswdOk.getText().trim())){
                        new MyAlert(Alert.AlertType.ERROR, "确认密码不能为空").show();
                        return;
                    }
                    if(!tfPasswd.getText().trim().equals(tfPasswdOk.getText().trim())) {
                        new MyAlert(Alert.AlertType.ERROR, "两次输入的新密码不一致").show();
                        return;
                    }
                    UpdatePassWordAction updateAction = new UpdatePassWordAction();
                    String password = new SaltUtil(tfUser.getText().trim(), "MD5").encode(tfPasswdOk.getText().trim());
                    updateAction.updatePassword(password,tfUser.getText().trim());
                    new MyAlert(Alert.AlertType.INFORMATION, "密码修改成功").show();
                }
            });

        });

        btn_setting.setOnAction(event -> {

            Dialog<String> dialog = new Dialog<>();
            dialog.setTitle("参数配置");
            dialog.setResizable(true);
            DialogPane pane = dialog.getDialogPane();
            pane.setPrefSize(500,200);
            Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
            stage.getIcons().add(new Image(ImageSrc.lOGO_PATH));
            GridPane gridPane = new GridPane();
            // 编辑机器人配置
            Button robotConfig = new Button("编辑机器人配置");

            // 机器人测试
            Button robotTest = new Button("机器人测试");
            robotTest.setAlignment(Pos.CENTER_RIGHT);
            gridPane.setVgap(10);
            gridPane.add(robotConfig,1,1);
            HBox temp = new HBox();
            temp.setAlignment(Pos.CENTER_RIGHT);
            temp.getChildren().add(robotTest);
            gridPane.add(temp,2,1);
            gridPane.setAlignment(Pos.CENTER);
            LoginDto loginDto =(LoginDto)ClientSession.getAttribute("user");
            Label lIpAdress = new Label("IP地址: ");
            lIpAdress.setAlignment(Pos.CENTER_RIGHT);
            gridPane.add(lIpAdress,1,2);
            TextField TfAdress = new TextField(StringUtils.isBlank(loginDto.getIpAddr())?"http://127.0.0.1:56001/lstaskpro":loginDto.getIpAddr());
            TfAdress.setPrefWidth(300);
            TfAdress.setPrefHeight(30);
            gridPane.add(TfAdress,2,2);

            Label lToken = new Label("TOKEN令牌: ");
            lToken.setAlignment(Pos.CENTER_RIGHT);
            gridPane.add(lToken,1,3);
            TextField tfToken = new TextField(loginDto.getTokens());
            tfToken.setPrefWidth(300);
            tfToken.setPrefHeight(30);
            gridPane.add(tfToken,2,3);
            pane.setContent(gridPane);

             // 为按钮添加点击事件处理程序
            robotTest.setOnAction(e -> {
                String filePath = "";
                String fileId = "test";
                String sbYearType = "年度";
                String sbYear = "2025";
                String fileName = "测试";
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("fun", "new_task");
                params.put("token", loginDto.getTokens());
                List<RobotPlanBean> data = new ArrayList();
                params.put("data", data);
                List<RobotProjectInfoBean> task_robots = new ArrayList();
                List<RobotOutParams> robot_ipars = new ArrayList();
                //计划信息
                RobotOutParams outParams0 = new RobotOutParams();
                outParams0.setPins_pin_name("filepath");
                outParams0.setPins_pin_defval(filePath);

                RobotOutParams outParams1 = new RobotOutParams();
                outParams1.setPins_pin_name("creditCode");
                outParams1.setPins_pin_defval(loginDto.getCreditCode());

                RobotOutParams outParams2 = new RobotOutParams();
                outParams2.setPins_pin_name("id");
                outParams2.setPins_pin_defval(fileId);
                RobotOutParams outParams3 = new RobotOutParams();
                outParams3.setPins_pin_name("sbYear");
                outParams3.setPins_pin_defval(sbYear);
                RobotOutParams outParams4 = new RobotOutParams();
                outParams4.setPins_pin_name("sbYearType");
                outParams4.setPins_pin_defval(sbYearType);
                RobotOutParams outParams5 = new RobotOutParams();
                outParams5.setPins_pin_name("companyName");
                outParams5.setPins_pin_defval(loginDto.getCompanyName());

                RobotOutParams outParams6 = new RobotOutParams();
                outParams6.setPins_pin_name("fileName");
                outParams6.setPins_pin_defval(fileName);

                robot_ipars.add(outParams0);
                robot_ipars.add(outParams6);
                robot_ipars.add(outParams1);
                robot_ipars.add(outParams5);
                robot_ipars.add(outParams2);
                robot_ipars.add(outParams3);
                robot_ipars.add(outParams4);

                RobotProjectInfoBean projectInfoBean = new RobotProjectInfoBean();
                projectInfoBean.setRobot_iscon("0");

                projectInfoBean.setRobot_name("机器人测试");
                //projectInfoBean.setRobot_ver("1.0.0.0");
                projectInfoBean.setRobot_ipars(robot_ipars);
                task_robots.add(projectInfoBean);

                RobotPlanBean planBean = new RobotPlanBean();
                planBean.setTask_robots(task_robots);
                planBean.setTask_name("税智报报送任务");
                String strDate = DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
                planBean.setTask_ontime(strDate);
                planBean.setTask_isVideo(3);
                planBean.setTask_overTime(1440);
                planBean.setTask_logLevel("3");
                planBean.setTask_runTime("0");
                planBean.setTask_reCount("0");
                data.add(planBean);
                String pushUrl ="";
                try {
                    String paras = JSONUtil.toJsonStr(params);
                    //new MyAlert(Alert.AlertType.INFORMATION, paras).show();http://127.0.0.1:56001
                    pushUrl = loginDto.getIpAddr();
                    HttpClientUtil.postJson(pushUrl,params);
                    new MyAlert(Alert.AlertType.INFORMATION, "测试成功.").show();
                } catch (Exception ex) {
                    new MyAlert(Alert.AlertType.ERROR, "服务地址不存在:".concat(pushUrl)).show();
                    ex.printStackTrace();
                }
            });

            // 为按钮添加点击事件处理程序
            robotConfig.setOnAction(e -> {
                try {
                    // 构建 bat 文件的路径
                    String batFilePath = "../LSPRO_Ent/执行器.bat";
                    // 创建 ProcessBuilder 对象
                    ProcessBuilder processBuilder = new ProcessBuilder(batFilePath);
                    // 启动进程
                    Process process = processBuilder.start();
                    // 等待进程执行完成
                    int exitCode = process.waitFor();
                    new MyAlert(Alert.AlertType.INFORMATION, "执行器-调用成功.").show();
                } catch (IOException | InterruptedException ioe) {
                    new MyAlert(Alert.AlertType.ERROR, "执行器-调用失败！").show();
                    ioe.printStackTrace();
                }
            });

            // 设置按钮和事件处理（可选）
            ButtonType buttonTypeOK = new ButtonType("确定");
             pane.getButtonTypes().add(buttonTypeOK);
            pane.getButtonTypes().add(ButtonType.CANCEL);
            dialog.setResultConverter(dialogButton -> dialogButton == buttonTypeOK ? "OK" : null);
            dialog.showAndWait().ifPresent(response -> {
                if ("OK".equals(response)) {
                    UpdateSystemSettingAction updateAction = new UpdateSystemSettingAction();
                    updateAction.updateSetting(TfAdress.getText(),tfToken.getText(),loginDto.getId());
                    ((LoginDto) ClientSession.getAttribute("user")).setIpAddr(TfAdress.getText());
                    ((LoginDto) ClientSession.getAttribute("user")).setTokens(tfToken.getText());
                    new MyAlert(Alert.AlertType.INFORMATION, "参数配置完成").show();
                }
            });

        });


    }

    /**
     * 初始化左侧菜单
     */
    private void initLeftMenu() {

        leftMenuVb.getStylesheets().add("/css/leftmenu.css");

        Label companyLogo = new LeftMenuItemLabel("申报客户端");
//        ImageView img_company = new ImageView(ImageSrc.SEARCH_PATH);
//        companyLogo.setGraphic(img_company);
//        companyLogo.setStyle("-fx-font-size: 24px;-fx-text-fill: #00ff00;");
        //点击事件定义 end
        // 设置上下边距
//        companyLogo.setPadding(new Insets(10, 0, 8, 0));
//
//        leftMenuVb.getChildren().add(companyLogo);

//        Label standardSubLb = new LeftMenuItemLabel("标准科目");
//        standardSubLb.setStyle("-fx-font-size: 14px;");
//        standardSubLb.setCursor(Cursor.HAND);
//        standardSubLb.setOnMouseClicked(event -> addTab(StandardSubTab.getInstance()));
//        leftMenuVb.getChildren().add(standardSubLb);
        //负债表-科目匹配
        Label subjectMatchLb = new LeftMenuItemLabel("余额表-科目匹配");
        ImageView subjectMatchImg = new ImageView(ImageSrc.SUBMAP_PATH);
        subjectMatchLb.setGraphic(subjectMatchImg);
        subjectMatchLb.setStyle("-fx-font-size: 14px;");
        subjectMatchLb.setCursor(Cursor.HAND);
        subjectMatchLb.setPrefHeight(LeftMenuItemLabel.LEFT_MENUITEM_SIZE);
        subjectMatchLb.setOnMouseClicked(event -> addTab(SubjectMatchTab.getInstance()));
        leftMenuVb.getChildren().add(subjectMatchLb);

        //负债表-科目匹配
        Label debtSubjectMatchLb = new LeftMenuItemLabel("负债表-科目匹配");
        ImageView debtSubjectMatchImg = new ImageView(ImageSrc.SUBMAP_PATH);
        debtSubjectMatchLb.setGraphic(debtSubjectMatchImg);
        debtSubjectMatchLb.setStyle("-fx-font-size: 14px;");
        debtSubjectMatchLb.setCursor(Cursor.HAND);
        debtSubjectMatchLb.setPrefHeight(LeftMenuItemLabel.LEFT_MENUITEM_SIZE);
        debtSubjectMatchLb.setOnMouseClicked(event -> addTab(SubjectMatchTab.getInstance()));
        leftMenuVb.getChildren().add(subjectMatchLb);


        Label dataImortLb = new LeftMenuItemLabel("余额表导入");
        ImageView dataImortImg = new ImageView(ImageSrc.IMP_RECORD_PATH);
        dataImortLb.setGraphic(dataImortImg);
        dataImortLb.setStyle("-fx-font-size: 14px;");
        dataImortLb.setCursor(Cursor.HAND);
        dataImortLb.setPrefHeight(LeftMenuItemLabel.LEFT_MENUITEM_SIZE);
        dataImortLb.setOnMouseClicked(event -> addTab(DataImportTab.getInstance()));
        leftMenuVb.getChildren().add(dataImortLb);
        Label declarationRecord = new LeftMenuItemLabel("申报记录");
        ImageView declarationImg = new ImageView(ImageSrc.EXCEL_RECORD_PATH);
        declarationRecord.setGraphic(declarationImg);
        declarationRecord.setStyle("-fx-font-size: 14px;");
        declarationRecord.setCursor(Cursor.HAND);
        declarationRecord.setOnMouseClicked(event -> addTab(DeclarationRecordTab.getInstance()));
        leftMenuVb.getChildren().add(declarationRecord);

    }

    /**
     * 左侧菜单按钮Label，事先设置好通用样式
     */
    private static class LeftMenuItemLabel extends Label {

        /**
         * 左侧按钮高度
         */
        private static final double LEFT_MENUITEM_SIZE = 30.0;

        /**
         * 最大尺寸数值
         */
        private static final double MAX_VALUE = Double.MAX_VALUE;

        private LeftMenuItemLabel(String text) {
            super(text);
            this.setPrefHeight(LEFT_MENUITEM_SIZE);
            this.setMaxWidth(MAX_VALUE);
            this.setAlignment(Pos.CENTER_LEFT);
            setPadding(new Insets(0, 0, 0, 20));
        }
    }
    /**
     * 修改密码处理
     */
    private  class UpdatePassWordAction{
        LoginService service = (LoginService) SpringUtil.getBean("LoginServiceImpl");
        public void updatePassword(String password,String username){
            service.updatePassword(password,username);
        }
   }

    /**
     * 修改系统设置处理
     */
    private  class UpdateSystemSettingAction{
        LoginService service = (LoginService) SpringUtil.getBean("LoginServiceImpl");
        public void updateSetting(String ip,String token,String username){
            service.updateSetting(ip,token,username);
        }
    }

    private void startSyncFileTask() {
       StandardSubService standardSubService = (StandardSubService) SpringUtil.getBean("StandardSubServiceImpl");
       LoginService service = (LoginService) SpringUtil.getBean("LoginServiceImpl");
        //同步数据
        LoginDto loginDto =(LoginDto)ClientSession.getAttribute("user");
        String strDate = DateUtil.formatDate(new Date(),"yyyy-MM-dd");
        if(StringUtils.isBlank(loginDto.getBaseDate()) || strDate.compareTo(loginDto.getBaseDate())>0){
            new Thread(() -> {
                HashMap<String, Object> request = new HashMap();
                String currentDate = "";
                if(StringUtils.isBlank(loginDto.getBaseDate())){
                    loginDto.setBaseDate("");
                }else{
                    currentDate = loginDto.getBaseDate().trim();
                }
                List<StandardSub>  standardSubs = standardSubService.list(new QueryWrapper<>());
                if(null != standardSubs && standardSubs.size() > 0 && !StringUtils.isBlank(currentDate)){
                    request.put("dateInfo", DesUtils.encrypt(currentDate,"Client_Sw@9701",false));
                }else{
                    request.put("dateInfo",  DesUtils.encrypt("2025-02-01","Client_Sw@9701",false));
                }
                try {
                    String rtnVal =  DesUtils.decrypt(standardSubService.getSubjectInfo(request),"Server_Sw@9702",false);
                    if (!StringUtils.isBlank(rtnVal)) {
                        JSONArray jsonArray = new JSONArray(rtnVal);
                        if(jsonArray.size()==0){
                            System.out.println("没有需要同步的数据");
                            return;
                        }else{
                            standardSubService.syncSubjectInfo(jsonArray);
                            service.updateBaseDate(strDate,loginDto.getId());
                        }
                    }

                } catch (Exception e) {
                    System.out.println("同步数据失败");
                    e.printStackTrace();
                }

            }).start();
        }
    }
}
